# -*- coding: utf-8 -*-
from datetime import datetime
import logging
import logging.handlers
import os
import sys

from config import config


class MyEmailLogHandler(logging.Handler):
    """
    自定义邮件日志
    """

    def __init__(self):
        super().__init__()
        self.subject = '动态IP更新程序发生错误'

    def emit(self, record):
        msg = self.format(record)
        msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
            config.email,
            ",".join(config.fault_to),
            self.subject,
            datetime.now, msg)
        print(msg)
        from email_operation import operation as email

        email.send(config.fault_to, self.subject, msg)


logger = logging.getLogger('get_ip_services')
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(name)-12s %(asctime)s %(levelname)-8s %(message)s')

base_path = os.path.split(os.path.realpath(__file__))[0]
file_handler = logging.handlers.TimedRotatingFileHandler(os.path.join(base_path, 'log', 'getip.log'), when='D', interval=1, backupCount=5, encoding='utf-8')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

std_handler = logging.StreamHandler(sys.stdout)
std_handler.setFormatter(formatter)
logger.addHandler(std_handler)

email_handler = MyEmailLogHandler()
email_handler.setFormatter(formatter)
email_handler.setLevel(logging.FATAL)
logger.addHandler(email_handler)